<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>店铺详情</span>
          <el-button type="primary" @click="goBack">返回</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <el-card style="background-color: #93B5E1; height: 100px; width: 100%;">
          <div class="shop-info" style="display: flex; padding: 20px;">
            <div class="shop-logo">
              <img :src="shopInfo.storeLogo" alt="店铺logo" 
                   style="width: 60px; height: 60px; border-radius: 8px; object-fit: cover; border: 2px solid #fff;" 
                   v-if="shopInfo.storeLogo" />
              <div v-else style="width: 60px; height: 60px; border-radius: 8px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center; border: 2px solid #fff;">
                <span style="color: #999; font-size: 12px;">暂无logo</span>
              </div>
            </div>
            <div class="shop-name" style="color: #FCFCFC; margin-left: 20px;  font-size: 20px; font-weight: bold;">
              <span>{{ shopInfo.storeName || '店铺名称未加载' }}</span>
            </div>
          </div>
        </el-card>

        <el-card style="margin-top: 20px; background-color: #F5F5F5; height: 80px;">
          <div style="display: flex; padding: 20px;">
            <div label="是否自营">
              <el-tag v-if="shopInfo.isSelfOperated === 0" size="large"
                style="background-color: #68CABE; color: white; border-color: #68CABE;">自营</el-tag>
              <el-tag v-else-if="shopInfo.isSelfOperated === 1" size="large"
                style="background-color: #FF3C2A; color: white; border-color: #FF3C2A;">非自营</el-tag>
              <span v-else>{{ shopInfo.isSelfOperated }}</span>
            </div>
            <div style="margin-left: 40px;">
              <!-- 开关根据店铺状态显示启用或禁用 -->
              <el-switch v-model="switchValue" class="ml-2" inline-prompt
                style="--el-switch-on-color: #FF5C58; --el-switch-off-color: #CCCCCC" active-text="启用"
                inactive-text="禁用" width="60" height="40" :disabled="true" />
            </div>
          </div>
        </el-card>


        <!-- 公司信息 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <span style="font-weight: bold; color: #67C23A;">公司信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="公司名称">
              {{ shopInfo.companyName }}
            </el-descriptions-item>
            <el-descriptions-item label="公司电话">
              {{ shopInfo.companyPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="员工总数">
              {{ shopInfo.employeeCount }}
            </el-descriptions-item>
            <el-descriptions-item label="注册资金(万)">
              {{ shopInfo.registeredCapital }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人姓名">
              {{ shopInfo.contactName }}
            </el-descriptions-item>
            <el-descriptions-item label="电子邮箱">
              {{ shopInfo.email }}
            </el-descriptions-item>
            <el-descriptions-item label="公司地址" :span="2">
              <!-- 公司地址=公司所在地+公司实际地址 -->
              {{ shopInfo.companyLocation + shopInfo.companyAddress }}
            </el-descriptions-item>
            <!-- <el-descriptions-item label="公司所在地">
               {{ shopInfo.companyLocation }}
             </el-descriptions-item>
             <el-descriptions-item label="公司实际地址" :span="2">
               {{ shopInfo.companyAddress }}
             </el-descriptions-item> -->


            <el-descriptions-item label="法定经营范围" :span="2">
              {{ shopInfo.businessScope }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 店铺信息 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <span style="font-weight: bold; color: #409EFF;">基本信息</span>
          </template>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="商家账号">
              {{ shopInfo.memberName }}
            </el-descriptions-item>
            <el-descriptions-item label="库存预警数">
              {{ shopInfo.stockWarningNum }}
            </el-descriptions-item>
            <el-descriptions-item label="店铺名称">
              {{ shopInfo.storeName }}
            </el-descriptions-item>
            <el-descriptions-item label="店铺地址">
              <!-- 店铺地址=店铺所在地+店铺详细地址 -->
              {{ shopInfo.storeLocation + shopInfo.storeAddress }}
            </el-descriptions-item>

            <!-- <el-descriptions-item label="店铺所在地">
               {{ shopInfo.storeLocation }}
             </el-descriptions-item>
             <el-descriptions-item label="店铺详细地址" :span="2">
               {{ shopInfo.storeAddress }}
             </el-descriptions-item> -->
            <el-descriptions-item label="店铺定位" :span="2">
              {{ shopInfo.location }}
            </el-descriptions-item>
            <el-descriptions-item label="经营范围" :span="2">
              {{ shopInfo.scope }}
            </el-descriptions-item>
            <el-descriptions-item label="店铺简介" :span="2">
              {{ shopInfo.storeDescription }}
            </el-descriptions-item>


          </el-descriptions>
        </el-card>



        <!-- 收货信息 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <span style="font-weight: bold; color: #E6A23C;">收货信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="收货人姓名">
              {{ shopInfo.receiverName }}
            </el-descriptions-item>
            <el-descriptions-item label="收件人手机">
              {{ shopInfo.receiverPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="详细地址" :span="2">
              {{ shopInfo.receiverAddressDetail }}
            </el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">
              {{ shopInfo.receiverAddress }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 证件信息 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <span style="font-weight: bold; color: #F56C6C;">法人信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="法人姓名">
              {{ shopInfo.legalPersonName }}
            </el-descriptions-item>
            <el-descriptions-item label="法人身份证">
              {{ shopInfo.legalPersonId }}
            </el-descriptions-item>
            <el-descriptions-item label="身份证照片" :span="2">
              <div v-if="shopInfo.legalPersonIdPhoto" style="display: flex; gap: 10px; flex-wrap: wrap;">
                <img v-for="(photo, index) in getPhotoArray(shopInfo.legalPersonIdPhoto)" 
                     :key="index" 
                     :src="photo" 
                     alt="身份证照片"
                     style="width: 150px; height: 100px; object-fit: cover; border-radius: 6px; border: 1px solid #ddd;" />
              </div>
              <span v-else style="color: #999;">暂无照片</span>
            </el-descriptions-item>
            <el-descriptions-item label="营业执照号">
              {{ shopInfo.businessLicenseNo }}
            </el-descriptions-item>
            <el-descriptions-item label="营业执照电子照片" :span="2">
              <img v-if="shopInfo.businessLicenseImage" :src="shopInfo.businessLicenseImage" alt="营业执照电子照片"
                style="width: 200px; height: 140px; object-fit: cover; border-radius: 6px; border: 1px solid #ddd;" />
              <span v-else style="color: #999;">暂无照片</span>
            </el-descriptions-item>
            <el-descriptions-item label="银行名称">
              {{ shopInfo.bankAccountName }}
            </el-descriptions-item>
            <el-descriptions-item label="银行账号">
              {{ shopInfo.bankAccountNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="银行支行名称">
              {{ shopInfo.bankBranchName }}
            </el-descriptions-item>
            <el-descriptions-item label="银行支行联行号">
              {{ shopInfo.bankBranchCode }}
            </el-descriptions-item>
            <el-descriptions-item label="结算日期(1-31)">
              {{ shopInfo.settlementDate }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>


        <!-- 时间信息
         <el-card style="margin-top: 20px;">
           <template #header>
             <span style="font-weight: bold; color: #607D8B;">时间信息</span>
           </template>
           <el-descriptions :column="2" border>
             <el-descriptions-item label="创建时间">
               {{ parseTime(shopInfo.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
             </el-descriptions-item>
             <el-descriptions-item label="最后更新时间">
               {{ parseTime(shopInfo.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
             </el-descriptions-item>
           </el-descriptions>
         </el-card> -->



        <el-card style="margin-top: 20px;">
          <template #header>
            <span style="font-weight: bold; color: #F56C6C;">订单信息</span>
          </template>
          <!-- 标签页，标签页内容为TA的订单，TA的退货单，TA的退款单 -->
          <!-- 数据根据店铺id获取：订单、退货单、退款单-->
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="TA的订单" name="order">
              <!-- 订单数据根据店铺id获取：订单、退货单、退款单-->
              <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="订单号" prop="orderId">
                  <el-input v-model="queryParams.orderId" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="订单状态" prop="orderStatus" style="width: 300px;">
                  <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态">
                    <!-- 根据实际的订单状态值设置选项 -->
                    <el-option label="未付款" value="UNPAID" />
                    <el-option label="已付款" value="PAID" />
                    <el-option label="待发货" value="WAIT_DELIVERY" />
                    <el-option label="已发货" value="DELIVERED" />
                    <el-option label="已完成" value="COMPLETED" />
                    <el-option label="待核验" value="WAIT_VERIFY" />
                    <el-option label="已关闭" value="CLOSED" />
                    <el-option label="已取消" value="CANCELLED" />
                  </el-select>
                </el-form-item>
                <el-form-item label="支付状态" prop="payStatus" style="width: 300px;">
                  <el-select v-model="queryParams.payStatus" placeholder="请选择支付状态">
                    <!-- 根据实际的支付状态值设置选项 -->
                    <el-option label="未付款" value="UNPAID" />
                    <el-option label="已付款" value="PAID" />
                  </el-select>
                </el-form-item>
                <el-form-item label="订单类型" prop="orderType" style="width: 300px;">
                  <el-select v-model="queryParams.orderType" placeholder="请选择订单类型">
                    <el-option label="普通订单" value="0" />
                    <el-option label="拼团订单" value="1" />
                    <el-option label="秒杀订单" value="2" />
                    <el-option label="砍价订单" value="3" />
                  </el-select>
                </el-form-item>
                <el-form-item label="订单来源" prop="orderSource" style="width: 300px;">
                  <el-select v-model="queryParams.orderSource" placeholder="请选择订单来源">
                    <el-option label="PC" value="0" />
                    <el-option label="H5" value="1" />
                    <el-option label="小程序" value="2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="下单时间" prop="orderTime" style="width: 300px;">
                  <el-date-picker v-model="queryParams.orderTime" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 订单数据表格 -->
              <el-table v-loading="orderLoading" :data="orderList" style="width: 100%">
                <el-table-column label="订单编号" align="center" prop="orderId" />
                <el-table-column label="订单金额" align="center" prop="orderAmount">
                  <template #default="scope">
                    <span style="color: red;">￥{{ scope.row.orderAmount ? scope.row.orderAmount.toFixed(2) : '0.00'
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="订单类型" align="center" prop="orderType">
                  <template #default="scope">
                    <el-tag v-if="scope.row.orderType === 0" type="primary">普通订单</el-tag>
                    <el-tag v-else-if="scope.row.orderType === 1" type="success">拼团订单</el-tag>
                    <el-tag v-else-if="scope.row.orderType === 2" type="warning">秒杀订单</el-tag>
                    <el-tag v-else-if="scope.row.orderType === 3" type="danger">砍价订单</el-tag>
                    <el-tag v-else type="info">{{ scope.row.orderType }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="订单来源" align="center" prop="orderSource">
                  <template #default="scope">
                    <el-tag v-if="scope.row.orderSource === 0" type="primary">PC</el-tag>
                    <el-tag v-else-if="scope.row.orderSource === 1" type="success">H5</el-tag>
                    <el-tag v-else-if="scope.row.orderSource === 2" type="warning">小程序</el-tag>
                    <el-tag v-else type="info">{{ scope.row.orderSource }}</el-tag>
                  </template>
                </el-table-column>
                                  <el-table-column label="订单状态" align="center" prop="orderStatus">
                    <template #default="scope">
                     <!-- 字符串，直接是字符串，不需要转换 -->
                      <!-- 未付款，已付款，待发货，已发货，已完成，待核验，已关闭，已取消 -->
                      <el-tag v-if="scope.row.orderStatus === '未付款'" type="warning">未付款</el-tag>
                      <el-tag v-else-if="scope.row.orderStatus === '已付款'" type="success">已付款</el-tag>
                      <el-tag v-else-if="scope.row.orderStatus === '待发货'" type="primary">待发货</el-tag>
                      <el-tag v-else-if="scope.row.orderStatus === '已发货'" type="info">已发货</el-tag>
                      <el-tag v-else-if="scope.row.orderStatus === '已完成'" type="success">已完成</el-tag>
                      <el-tag v-else-if="scope.row.orderStatus === '待核验'" type="primary">待核验</el-tag>
                      <el-tag v-else-if="scope.row.orderStatus === '已关闭'" type="info">已关闭</el-tag>
                      <el-tag v-else-if="scope.row.orderStatus === '已取消'" type="danger">已取消</el-tag>
                      <el-tag v-else type="info">{{ scope.row.orderStatus }}</el-tag>
                    </template>
                  </el-table-column>
              <el-table-column label="支付状态" align="center" prop="paymentStatus">
                  <template #default="scope">
                    <!-- 字符串，直接是字符串，不需要转换 -->
                    <!-- 已付款，未付款 -->
                    <el-tag v-if="scope.row.paymentStatus === '已付款'" type="success">已付款</el-tag>
                    <el-tag v-else-if="scope.row.paymentStatus === '未付款'" type="warning">未付款</el-tag>
                    <el-tag v-else type="info">{{ scope.row.paymentStatus }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="投诉状态" align="center" prop="complaintStatus">
                  <template #default="scope">
                    {{ scope.row.complaintStatus || '无投诉' }}
                  </template>
                </el-table-column>
                <el-table-column label="购买店铺" align="center">
                  <template #default="scope">
                    {{ scope.row.orderProductList && scope.row.orderProductList.length > 0 ? scope.row.orderProductList[0].shopName : '暂无' }}
                  </template>
                </el-table-column>
                <el-table-column label="下单时间" align="center" prop="createTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页组件 -->
              <pagination v-show="orderTotal > 0" :total="orderTotal" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getOrderList" />
            </el-tab-pane>
            <el-tab-pane label="TA的退货单" name="return">
              <el-form :model="returnQueryParams" ref="returnQueryRef" :inline="true" v-show="showSearch"
                label-width="68px">
                <el-form-item label="订单号" prop="orderId">
                  <el-input v-model="returnQueryParams.orderId" placeholder="请输入订单号" clearable
                    @keyup.enter="handleReturnQuery" />
                </el-form-item>
                <el-form-item label="售后单号" prop="serviceNo">
                  <el-input v-model="returnQueryParams.serviceNo" placeholder="请输入售后单号" clearable
                    @keyup.enter="handleReturnQuery" />
                </el-form-item>
                <el-form-item label="售后状态" prop="afterSalesStatus" style="width: 300px;">
                  <el-select v-model="returnQueryParams.afterSalesStatus" placeholder="请选择售后状态">
                    <el-option label="申请中" value="1" />
                    <el-option label="通过售后" value="2" />
                    <el-option label="拒绝售后" value="3" />
                    <el-option label="待收货" value="4" />
                    <el-option label="确认收货" value="5" />
                    <el-option label="完成售后" value="6" />
                    <el-option label="卖家终止售后" value="7" />
                    <el-option label="买家取消售后" value="8" />
                  </el-select>
                </el-form-item>
                <el-form-item label="申请时间" prop="applyTime" style="width: 300px;">
                  <el-date-picker v-model="returnQueryParams.applyTime" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleReturnQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetReturnQuery">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 退货单数据表格 -->
              <el-table v-loading="returnLoading" :data="returnList" style="width: 100%">
                <el-table-column label="售后服务单号" align="center" prop="serviceNo" />
                <el-table-column label="订单编号" align="center" prop="orderId" />
                <el-table-column label="商品" align="center">
                  <!-- 商品=商品图片+商品名称 -->
                  <template #default="scope">
                    <div>
                      <image-preview :src="scope.row.orderProductList && scope.row.orderProductList.length > 0 ? scope.row.orderProductList[0].productImage : ''" :width="50" :height="50" />
                      <span>{{ scope.row.orderProductList && scope.row.orderProductList.length > 0 ? scope.row.orderProductList[0].productName : '暂无' }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="会员名称" align="center" prop="buyerName" />
                <el-table-column label="商家名称" align="center">
                  <template #default="scope">
                    {{ scope.row.orderProductList && scope.row.orderProductList.length > 0 ? scope.row.orderProductList[0].shopName : '暂无' }}
                  </template>
                </el-table-column>
                <el-table-column label="售后金额" align="center" prop="serviceAmount">
                  <template #default="scope">
                    <span style="color: red;">￥{{ scope.row.serviceAmount ? scope.row.serviceAmount.toFixed(2) : '0.00'
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="售后类型" align="center" prop="afterSalesType">
                  <template #default="scope">
                    <el-tag v-if="scope.row.afterSalesType === 1" type="warning">退货</el-tag>
                    <el-tag v-else-if="scope.row.afterSalesType === 2" type="danger">退款</el-tag>
                    <el-tag v-else type="info">{{ scope.row.afterSalesType }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="售后状态" align="center" prop="afterSalesStatus">
                  <template #default="scope">
                    {{ getAfterSalesStatusText(scope.row.afterSalesStatus) }}
                  </template>
                </el-table-column>
                <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页组件 -->
              <pagination v-show="returnTotal > 0" :total="returnTotal" v-model:page="returnQueryParams.pageNum"
                v-model:limit="returnQueryParams.pageSize" @pagination="getReturnList" />
            </el-tab-pane>
            <el-tab-pane label="TA的退款单" name="refund">
              <el-form :model="refundQueryParams" ref="refundQueryRef" :inline="true" v-show="showSearch"
                label-width="68px">
                <el-form-item label="订单号" prop="orderId">
                  <el-input v-model="refundQueryParams.orderId" placeholder="请输入订单号" clearable
                    @keyup.enter="handleRefundQuery" />
                </el-form-item>
                <el-form-item label="售后单号" prop="serviceNo">
                  <el-input v-model="refundQueryParams.serviceNo" placeholder="请输入售后单号" clearable
                    @keyup.enter="handleRefundQuery" />
                </el-form-item>
                <el-form-item label="退款状态" prop="refundStatus" style="width: 300px;">
                  <el-select v-model="refundQueryParams.refundStatus" placeholder="请选择退款状态">
                    <el-option label="待退款" value="0" />
                    <el-option label="已退款" value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item label="申请时间" prop="applyTime" style="width: 300px;">
                  <el-date-picker v-model="refundQueryParams.applyTime" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleRefundQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetRefundQuery">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 退款单数据表格 -->
              <el-table v-loading="refundLoading" :data="refundList" style="width: 100%">
                <el-table-column label="售后服务单号" align="center" prop="serviceNo" />
                <el-table-column label="订单编号" align="center" prop="orderId" />
                <el-table-column label="商品" align="center">
                  <!-- 商品=商品图片+商品名称 -->
                  <template #default="scope">
                    <div>
                      <image-preview :src="scope.row.orderProductList && scope.row.orderProductList.length > 0 ? scope.row.orderProductList[0].productImage : ''" :width="50" :height="50" />
                      <span>{{ scope.row.orderProductList && scope.row.orderProductList.length > 0 ? scope.row.orderProductList[0].productName : '暂无' }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="会员名称" align="center" prop="buyerName" />
                <el-table-column label="商家名称" align="center">
                  <template #default="scope">
                    {{ scope.row.orderProductList && scope.row.orderProductList.length > 0 ? scope.row.orderProductList[0].shopName : '暂无' }}
                  </template>
                </el-table-column>
                <el-table-column label="售后金额" align="center" prop="serviceAmount">
                  <template #default="scope">
                    <span style="color: red;">￥{{ scope.row.serviceAmount ? scope.row.serviceAmount.toFixed(2) : '0.00'
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="售后类型" align="center" prop="afterSalesType">
                  <template #default="scope">
                    <el-tag v-if="scope.row.afterSalesType === 1" type="warning">退货</el-tag>
                    <el-tag v-else-if="scope.row.afterSalesType === 2" type="danger">退款</el-tag>
                    <el-tag v-else type="info">{{ scope.row.afterSalesType }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="售后状态" align="center" prop="afterSalesStatus">
                  <template #default="scope">
                    {{ getAfterSalesStatusText(scope.row.afterSalesStatus) }}
                  </template>
                </el-table-column>


                <el-table-column label="用户提交退款申请的时间" align="center" prop="applyTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页组件 -->
              <pagination v-show="refundTotal > 0" :total="refundTotal" v-model:page="refundQueryParams.pageNum"
                v-model:limit="refundQueryParams.pageSize" @pagination="getRefundList" />
            </el-tab-pane>
          </el-tabs>
        </el-card>


      </div>
    </el-card>
  </div>
</template>

<script setup name="ShopinfoDetail">
import { getShopinfo } from "@/api/dianpu/shopinfo"
import { listOrder, getOrdersByShopId } from "@/api/orders/order"
import { listSale } from "@/api/orders/sale"
import { listRefund } from "@/api/orders/refund"
import { useRoute, useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

const loading = ref(true)
const shopInfo = ref({})

// 订单相关数据
const orderLoading = ref(false)
const orderList = ref([])
const orderTotal = ref(0)
const activeTab = ref('order')
const showSearch = ref(true)

// 退货单相关数据
const returnLoading = ref(false)
const returnList = ref([])
const returnTotal = ref(0)

// 退款单相关数据
const refundLoading = ref(false)
const refundList = ref([])
const refundTotal = ref(0)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderId: '',
  buyerName: '',
  invoiceInfo: '',
  storeId: '' // 店铺ID
})

// 退货单查询参数
const returnQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderId: '',
  serviceNo: '',
  afterSalesStatus: '',
  applyTime: '',
  storeId: '' // 店铺ID
})

// 退款单查询参数
const refundQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderId: '',
  serviceNo: '',
  refundStatus: '',
  applyTime: '',
  storeId: '' // 店铺ID
})

/** 售后状态文本 */
function getAfterSalesStatusText(status) {
  const statusMap = {
    '1': '申请中',
    '2': '通过售后',
    '3': '拒绝售后',
    '4': '待收货',
    '5': '确认收货',
    '6': '完成售后',
    '7': '卖家终止售后',
    '8': '买家取消售后'
  }
  return statusMap[status] || status || '未知'
}
// 计算开关状态：只有店铺状态为开启中(0)时为启用，其他都为禁用
const switchValue = computed(() => {
  return shopInfo.value.storeStatus === 0
})

/** 处理图片数组 */
function getPhotoArray(photos) {
  if (!photos) return []
  if (typeof photos === 'string') {
    // 如果是逗号分隔的字符串，分割成数组
    return photos.split(',').filter(photo => photo.trim())
  }
  if (Array.isArray(photos)) {
    return photos
  }
  return [photos]
}

/** 获取店铺详情 */
function getShopDetail() {
  const id = route.params.id || route.query.id;
  console.log('详情页面 - 接收到的ID参数:', id)
  console.log('详情页面 - 路由信息:', route)
  
  if (!id) {
    console.error('详情页面 - 错误: ID参数为空')
    proxy.$modal.msgError("店铺ID不能为空")
    goBack()
    return
  }

  loading.value = true
  console.log('详情页面 - 开始请求API, ID:', id)
  
  getShopinfo(id).then(response => {
    console.log('详情页面 - API请求成功')
    console.log('详情页面 - 完整响应:', response)
    console.log('详情页面 - 响应数据:', response.data)
    console.log('详情页面 - 数据类型:', typeof response.data)
    console.log('详情页面 - 是否为空:', !response.data)
    
    if (!response.data) {
      console.error('详情页面 - 错误: 返回数据为空')
      proxy.$modal.msgError("获取的店铺数据为空")
      loading.value = false
      return
    }
    
    shopInfo.value = response.data
    console.log('详情页面 - shopInfo已设置:', shopInfo.value)
    loading.value = false

    // 设置店铺ID到查询参数中
    queryParams.value.storeId = id
    returnQueryParams.value.storeId = id
    refundQueryParams.value.storeId = id
    // 获取订单列表
    getOrderList()
  }).catch((error) => {
    console.error('详情页面 - API请求失败:', error)
    console.error('详情页面 - 错误详情:', error.response)
    console.error('详情页面 - 错误信息:', error.message)
    loading.value = false
    proxy.$modal.msgError("获取店铺详情失败: " + (error.message || '未知错误'))
    goBack()
  })
}

/** 获取订单列表 */
function getOrderList() {
  if (!queryParams.value.storeId) {
    console.log('订单查询失败：没有店铺ID')
    return
  }

  orderLoading.value = true
  // 使用新的API方法，通过店铺ID查询订单信息
  console.log('订单查询参数 - 店铺ID:', queryParams.value.storeId)
  getOrdersByShopId(queryParams.value.storeId).then(response => {
    console.log('订单API响应:', response)
    console.log('订单原始数据:', response.data)
    console.log('订单rows数据:', response.rows)
    orderList.value = response.data || response.rows || []
    orderTotal.value = response.total || orderList.value.length
    console.log('最终订单列表:', orderList.value)
    console.log('订单总数:', orderTotal.value)
    orderLoading.value = false
  }).catch(error => {
    console.error('获取订单列表失败:', error)
    console.error('错误详情:', error.response)
    orderLoading.value = false
    proxy.$modal.msgError("获取订单列表失败: " + (error.message || '未知错误'))
  })
}

/** 获取退货单列表 */
function getReturnList() {
  if (!returnQueryParams.value.storeId) {
    return
  }

  returnLoading.value = true
  console.log('退货单查询参数 - 店铺ID:', returnQueryParams.value.storeId)
  // 使用订单API获取数据，然后过滤出退货相关的订单
  getOrdersByShopId(returnQueryParams.value.storeId).then(response => {
    const allOrders = response.data || response.rows || []
      // 过滤出有退货信息的订单（根据退货数量大于0来判断）
  returnList.value = allOrders.filter(order => {
    // 检查orderProductList中是否有退货数量大于0的商品
    return order.orderProductList && order.orderProductList.some(product => 
      product.refundQuantity && product.refundQuantity > 0
    )
  })
    returnTotal.value = returnList.value.length
    returnLoading.value = false
    console.log('退货单数据:', returnList.value)
  }).catch(error => {
    console.error('获取退货单列表失败:', error)
    returnLoading.value = false
    proxy.$modal.msgError("获取退货单列表失败")
  })
}

/** 获取退款单列表 */
function getRefundList() {
  if (!refundQueryParams.value.storeId) {
    return
  }

  refundLoading.value = true
  console.log('退款单查询参数 - 店铺ID:', refundQueryParams.value.storeId)
  // 使用订单API获取数据，然后过滤出退款相关的订单
  getOrdersByShopId(refundQueryParams.value.storeId).then(response => {
    const allOrders = response.data || response.rows || []
    // 过滤出有退款信息的订单（可以根据订单状态或其他字段来判断）
    refundList.value = allOrders.filter(order => {
      // 这里可以根据具体的退款状态字段来过滤，暂时显示所有订单作为退款单
      return order.orderStatus === 'REFUNDED' || order.orderStatus === 'CANCELLED'
    })
    refundTotal.value = refundList.value.length
    refundLoading.value = false
    console.log('退款单数据:', refundList.value)
  }).catch(error => {
    console.error('获取退款单列表失败:', error)
    refundLoading.value = false
    proxy.$modal.msgError("获取退款单列表失败")
  })
}

/** 搜索订单 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getOrderList()
}

/** 搜索退货单 */
function handleReturnQuery() {
  returnQueryParams.value.pageNum = 1
  getReturnList()
}

/** 搜索退款单 */
function handleRefundQuery() {
  refundQueryParams.value.pageNum = 1
  getRefundList()
}

/** 重置搜索 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderId: '',
    buyerName: '',
    invoiceInfo: '',
    storeId: queryParams.value.storeId // 保持店铺ID
  }
  getOrderList()
}

/** 重置退货单搜索 */
function resetReturnQuery() {
  returnQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderId: '',
    serviceNo: '',
    afterSalesStatus: '',
    applyTime: '',
    storeId: returnQueryParams.value.storeId // 保持店铺ID
  }
  getReturnList()
}

/** 重置退款单搜索 */
function resetRefundQuery() {
  refundQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderId: '',
    serviceNo: '',
    refundStatus: '',
    applyTime: '',
    storeId: refundQueryParams.value.storeId // 保持店铺ID
  }
  getRefundList()
}

/** 标签页切换 */
function handleTabClick(tab) {
  console.log('切换到标签页:', tab.props.name)
  if (tab.props.name === 'return') {
    getReturnList()
  } else if (tab.props.name === 'refund') {
    getRefundList()
  } else if (tab.props.name === 'order') {
    getOrderList()
  }
}

/** 查看订单详情 */
function handleViewOrder(row) {
  console.log('查看订单详情:', row)
  // 这里可以跳转到订单详情页面或打开详情弹窗
  proxy.$modal.msgInfo(`查看订单: ${row.orderSn}`)
}

// 监听路由变化
watch(() => route.query.id, (newId) => {
  if (newId) {
    getShopDetail()
  }
})

/** 返回列表页 */
function goBack() {
  router.push('/dianpu/shopinfo')
}

// 页面加载时获取详情
onMounted(() => {
  getShopDetail()

  // 添加API测试
  setTimeout(() => {
    console.log('=== API测试开始 ===')
    const testId = route.params.id || route.query.id || 1
    console.log('测试ID:', testId)

    // 直接测试API调用
    fetch(`/api/dianpu/shopinfo/${testId}`)
      .then(response => {
        console.log('API响应状态:', response.status)
        return response.json()
      })
      .then(data => {
        console.log('API返回数据:', data)
        console.log('location字段:', data.data?.location)
      })
      .catch(error => {
        console.error('API测试失败:', error)
      })
  }, 1000)
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  margin: 20px;
}

.shop-info {
  display: flex;
  align-items: center;
}

.shop-logo img {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  border: 2px solid white;
  object-fit: cover;
}

.shop-name {
  margin-left: 20px;
  color: white;
  font-size: 20px;
  font-weight: bold;
}

/* 图片显示优化 */
:deep(.el-descriptions-item) img {
  transition: transform 0.3s ease;
  cursor: pointer;
}

:deep(.el-descriptions-item) img:hover {
  transform: scale(1.05);
}

/* 确保图片容器的布局 */
.photo-container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
</style>